<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="exhTitle">
        <el-input v-model="queryParams.exhTitle" placeholder="请输入标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="exhStatus">
        <el-select v-model="queryParams.exhStatus" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.vote_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['exhibition:exhibition:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['exhibition:exhibition:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['exhibition:exhibition:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['exhibition:exhibition:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="exhibitionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="作品展ID" align="center" prop="exhId" />
      <el-table-column label="标题" align="center" prop="exhTitle" />
      <el-table-column label="参与人数" align="center" prop="demo2" />
      <el-table-column label="图片" align="center" prop="exhImgPath" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.exhImgPath" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="exhVoteStart" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.exhVoteStart, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="exhVoteEnd" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.exhVoteEnd, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="exhStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.vote_status" :value="scope.row.exhStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['exhibition:exhibition:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['exhibition:exhibition:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-star-off"
            @click="handleVoteWorksDetail(scope.row)">投票详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-star-on" @click="handleVoteWorks(scope.row)">投票作品</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改投票管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="校区" prop="campusId">
        <el-select v-model="form.campusId" placeholder="请选择校区" clearable>
          <el-option v-for="item in campusList" :key="item.value" :label="item.campusName" :value="item.campusId" />
        </el-select>
      </el-form-item>
        <el-form-item label="标题" prop="exhTitle">
          <el-input v-model="form.exhTitle" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="图片" prop="exhImgPath">
          <el-upload class="upload-demo" drag action :multiple="false" :http-request="uploadImg"
            :show-file-list="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>

          <!-- 图片预览区域 -->
          <div v-if="form.exhImgPath" class="image-preview" style="max-width: 200px; margin-top: 10px;">
            <img :src="form.exhImgPath" alt="预览图" class="preview-image"
              style="width: 100%; max-height: 120px; object-fit: contain;">
          </div>
          <!-- <div v-if="form.exhImgPath" class="image-preview">
            <img :src="form.exhImgPath" alt="预览图" class="preview-image">
          </div> -->
        </el-form-item>
        <el-form-item label="开始时间" prop="exhVoteStart">
          <el-date-picker clearable v-model="form.exhVoteStart" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="exhVoteEnd">
          <el-date-picker clearable v-model="form.exhVoteEnd" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="exhStatus">
          <el-radio-group v-model="form.exhStatus">
            <el-radio v-for="dict in dict.type.vote_status" :key="dict.value" :label="parseInt(dict.value)">{{
              dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 投票作品弹窗 -->
    <el-dialog :title="'投票作品'" :visible.sync="voteDialogVisible" width="900px" append-to-body>
      <div style="display: flex;">
        <!-- 左侧选择区 -->
        <div style="width: 300px; margin-right: 24px;">
          <el-form label-width="60px">
            <el-form-item label="校区">
              <el-select v-model="voteSelect.campusId" placeholder="请选择校区" @change="onCampusChange" filterable>
                <el-option v-for="item in campusList" :key="item.id || item.campusId"
                  :label="item.name || item.campusName" :value="item.id || item.campusId" />
              </el-select>
            </el-form-item>
            <el-form-item label="班级">
              <el-select v-model="voteSelect.claId" placeholder="请选择班级" @change="onClassChange"
                :disabled="!voteSelect.campusId" filterable>
                <el-option v-for="item in classList" :key="item.id || item.claId" :label="item.claDescribe"
                  :value="item.claId" />
              </el-select>
            </el-form-item>
            <el-form-item label="学生">
              <el-select v-model="voteSelect.stuId" placeholder="请选择学生" @change="onStudentChange"
                :disabled="!voteSelect.claId" filterable>
                <el-option v-for="item in studentList" :key="item.id || item.stuId" :label="item.name || item.stuName"
                  :value="item.id || item.stuId" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <!-- 右侧作品区 -->
        <div style="flex: 1; min-height: 300px;">
          <div v-if="worksList.length === 0" style="color: #999; text-align: center; padding: 60px 0;">暂无作品</div>
          <el-row :gutter="16" v-else>
            <el-col :span="8" v-for="work in worksList" :key="work.artworksId" style="margin-bottom: 16px;">
              <div style="border: 1px solid #eee; border-radius: 6px; padding: 12px; text-align: center;">
                <!-- 作品图片 -->
                <img :src="work.artworkLink" alt="作品"
                  style="width: 100%; max-height: 120px; object-fit: contain; margin-bottom: 8px;" />
                <!-- 作品标题 -->
                <div style="margin-bottom: 8px;">{{ work.artworkTitle }}</div>
                <!-- 多选框 -->
                <el-checkbox v-model="work.checked" @change="onWorkSelect(work.artworksId)">
                </el-checkbox>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="voteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitVoteWorks">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExhibition, getExhibition, delExhibition, addExhibition, updateExhibition, getAllClassList, getAllStudentList, getAllWorks, insertWorks } from "@/api/exhibition/exhibition"
import { uploadIdCard } from "@/api/artGood/artGood"
import { listAllCampus } from '@/api/course/courseParent'


export default {
  name: "Exhibition",
  dicts: ['vote_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 投票管理表格数据
      exhibitionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        exhTitle: null,
        exhStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        exhTitle: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        exhStatus: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      },
      voteDialogVisible: false,
      campusList: [],
      classList: [],
      studentList: [],
      worksList: [],
      voteSelect: {
        campusId: null,
        claId: null,
        stuId: null
      },
      selectedWorks: {}, // { stuId: [{id: artworksId, title: artworkTitle, ...}, ...] }
    }
  },
  created() {
    this.getList()
    this.loadCampusList()
  },
  methods: {
    /** 查询投票管理列表 */
    getList() {
      this.loading = true
      listExhibition(this.queryParams).then(response => {
        this.exhibitionList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        exhId: null,
        exhTitle: null,
        demo2: null,
        exhImgPath: null,
        exhVoteStart: null,
        exhVoteEnd: null,
        exhStatus: null,
        exhSortOrder: null,
        exhCreateTime: null,
        exhUpdateTime: null,
        campusId: null,
        demo2: null,
        demo3: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.exhId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加投票管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const exhId = row.exhId || this.ids
      getExhibition(exhId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改投票管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.exhId != null) {
            updateExhibition(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addExhibition(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const exhIds = row.exhId || this.ids
      this.$modal.confirm('是否确认删除投票管理编号为"' + exhIds + '"的数据项？').then(function () {
        return delExhibition(exhIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('exhibition/exhibition/export', {
        ...this.queryParams
      }, `exhibition_${new Date().getTime()}.xlsx`)
    },

    // 上传图片，修改图片
    uploadImg(item) {
      const formData = new FormData();
      formData.append("file", item.file);

      uploadIdCard(formData)
        .then(res => {
          this.$modal.msgSuccess("上传成功");
          // 直接赋值给表单的goodPicture字段
          this.form.exhImgPath = res.data.file.url;
          console.log('图片URL已保存到表单:', this.form.exhImgPath);

          // 可选：上传成功后显示预览
          this.previewImage = res.data.file.url;
        })
        .catch(error => {
          this.$modal.msgError("上传失败: " + error.message);
          console.error('图片上传失败:', error);
        });
    },

    handleVoteWorks(row) {
      if (row && row.exhId) {
        this.voteSelect.exhId = row.exhId
      } else {
        this.voteSelect.exhId = null
      }
      this.voteDialogVisible = true
      this.resetVoteDialog()
      this.loadCampusList()
    },
    resetVoteDialog() {
      this.voteSelect = { campusId: null, claId: null, stuId: null, exhId: this.voteSelect.exhId }
      this.classList = []
      this.studentList = []
      this.worksList = []
    },
    loadCampusList() {
      listAllCampus().then(res => {
        this.campusList = res.data || []
        console.log(this.campusList, 999)
      })
    },
    onCampusChange(val) {
      console.log(this.voteSelect.campusId, 555)
      this.voteSelect.claId = null
      this.voteSelect.stuId = null
      this.classList = []
      this.studentList = []
      this.worksList = []
      if (this.voteSelect.campusId) {
        console.log(val, 444)
        getAllClassList(val).then(res => {
          console.log(res, 666)
          this.classList = res.data || []

        })
      }
    },
    onClassChange(val) {
      console.log(this.voteSelect.claId, 3333)
      this.voteSelect.stuId = null
      this.studentList = []
      this.worksList = []
      if (this.voteSelect.claId) {
        getAllStudentList(val).then(res => {
          console.log(this.studentList, 77776)
          this.studentList = res.data || []
          console.log(this.studentList, 786)
        })
      }
    },
    onStudentChange(val) {
      this.worksList = []
      console.log(this.voteSelect.stuId, 1111)
      if (this.voteSelect.stuId) {
        console.log(this.voteSelect.stuId, 8787)
        // 确保当前学生的选中作品数组存在
        if (!this.selectedWorks[val]) {
          this.selectedWorks[val] = []
        }

        getAllWorks(val).then(res => {
          console.log(res, 33334445)
          // 为每个作品添加 checked 属性，并回显已选作品
          this.worksList = (res.data || []).map(work => {
            // 检查该作品是否已被选中（回显）
            work.checked = this.selectedWorks[val].some(item => item.id === work.artworksId)
            return work
          })
        })
      }
    },
    onWorkSelect(artworksId) {
      console.log('选中/取消选中的作品ID:', artworksId)

      // 获取当前学生ID
      const stuId = this.voteSelect.stuId
      if (!stuId) return

      // 确保数组存在
      if (!this.selectedWorks[stuId]) {
        this.selectedWorks[stuId] = []
      }

      // 找到对应的作品
      const work = this.worksList.find(w => w.artworksId === artworksId)

      if (work && work.checked) {
        // 如果选中，添加完整作品信息到数组中
        if (!this.selectedWorks[stuId].some(item => item.id === artworksId)) {
          this.selectedWorks[stuId].push({
            workId: artworksId,
            formContent: work.artworkTitle,
            link: work.artworkLink,
            formSubmit: work.stuId

            // 可以添加更多你需要的作品信息
          })
        }
      } else {
        // 如果取消选中，从数组中移除
        this.selectedWorks[stuId] = this.selectedWorks[stuId].filter(item => item.id !== artworksId)
      }

      console.log('当前学生已选作品:', this.selectedWorks[stuId])
    },
    submitVoteWorks() {
      // 收集所有选中的作品ID到一个数组
      const allSelectedArtworkIds = [];
      const allSelectedArtworks = [];

      // 遍历所有学生的选择
      Object.keys(this.selectedWorks).forEach(stuId => {
        // 将该学生选择的作品添加到总数组中
        if (this.selectedWorks[stuId] && this.selectedWorks[stuId].length > 0) {
          // 添加ID到ID数组
          allSelectedArtworkIds.push(...this.selectedWorks[stuId].map(item => item.id));
          // 添加完整信息到作品数组
          allSelectedArtworks.push(...this.selectedWorks[stuId]);
        }
      });

      // 打印所有选中的作品ID
      console.log('所有选中的作品ID数组:', allSelectedArtworkIds);

      // 打印所有选中的作品完整信息（包含名称）
      console.log('所有选中的作品完整信息:', allSelectedArtworks);
      for (const element of allSelectedArtworks) {
        element.exhId = this.voteSelect.exhId
        element.campusId = this.voteSelect.campusId
      }

      insertWorks(allSelectedArtworks).then(res => {
        console.log(res, 123456)

        // 提交成功后清空所有数据
        this.selectedWorks = {}; // 清空所有已选作品
        this.worksList = []; // 清空当前作品列表
        this.studentList = []; // 清空学生列表
        this.classList = []; // 清空班级列表
        this.voteSelect = { campusId: null, claId: null, stuId: null, exhId: null }; // 重置选择

        // 关闭弹窗
        this.voteDialogVisible = false;
        this.$message.success('投票作品已保存成功');
      }).catch(error => {
        this.$message.error('保存失败: ' + (error.message || '未知错误'));
      });

      this.getList()
      // 如果只想看当前展览的所有选中作品
      console.log('当前展览ID:', this.voteSelect.exhId);
      console.log('当前展览下所有选中的作品:', this.selectedWorks);
    },

    handleVoteWorksDetail(row) {
      // 跳转到投票记录页面并传递展览ID作为查询参数
      this.$router.push({
        path: '/art/voteRecord',
        query: {
          exhTitle: row.exhTitle
        }
      });
    }
  }
}
</script>
